﻿#--------------------------------------------------------------------------------------------------------------------------------------------------------
#
# Mi-DevEnv			:	http://midevenv.codeplex.com 
#					:	(c) IT Bridge 2012
#					:	A concept originated by Chris Nurse
#
# Licence			:	GNU General Public License version 2 (GPLv2)
#					:	http://midevenv.codeplex.com/license
#
# Summary           :   Fix incompatibilities between CRM and K2
#
#--------------------------------------------------------------------------------------------------------------------------------------------------------

if ((Get-Module MDE-Common) -eq $null) {
    Import-Module MDE-Common
    }

Function InstallProduct() {

    # Find the service account for K2 application pool
    $user = Get-ADUser "MDE_K2_AppPoolSvc"

    # The account must be placed in the CRM PrivUserGroup, but this will have a weird GUID appended, so a wild card search is needed
    $crmGroup = Get-ADGroup -Filter * -SearchScopse Subtree | Where-Object {$_.Name -like "*PrivUserGroup*"} | Select-Object -First 1

    if ($user -ne $null -and $crmGroup -ne $null) {
        Write-Host "Fix up K2 / CRM compatibilities"
        Write-Host "-------------------------------"

        # Add the service account to the group
        try {
            Add-ADGroupMember -Identity $group -Members $user.samAccountName
            }
        catch {
            Write-Output "MDE_K2_AppPoolSvc already exists in CRM PrivUserGroup."
            }

        # Find where gacutil is installed
        $gacUtil = Get-ChildItem -Path "C:\Program Files (x86)" -Filter gacutil.exe -Recurse | Select-Object -First 1

        # Ensure the CRM SDK assembly isn't in the GAC, as K2 installs this which breaks CRM 2011
        if ($gacUtil -ne $null) {
            Start-Process -FilePath $gacUtil.FullName -ArgumentList "/u Microsoft.Xrm.Sdk"
           }
        }
    else {
        Write-Host "Either the K2 Service account or the CRM PrivUserGroup can not be detected."
        Write-Host "This indicates that either product is not detected, therefore no conflict can exist and no actions is required."
        }
    }

        
#region Metadata

Function GetInstallName() {
    return "CRM / K2 Fix"
    }
    
Function GetRequireRestart() {
    return $false
    }

Function GetPackageName() {
    return "K2CRMFIX"
    }

Function GetPackageDescription() {
    return "Fix compatibility between K2 and CRM"
    }

Function GetServerBuild() {
    return $false
    }
    
Function GetInstallPriority() {
    return 1100000
    }

#endregion